package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"net"
	"src/gRPC/gw2rpc/conf"
	gw "src/gRPC/proto"
)

//定义空接口
type DogService struct {
	gw.UnimplementedDogServiceServer
}

//实现方法
func (s *DogService) GetInfo(c context.Context, req *gw.DogRequest) (resp *gw.DogResponse, err error) {

	//获取参数
	var name = req.Name

	//@todo test client req timeout
	//time.Sleep(time.Second * 2)

	resp = &gw.DogResponse{
		Id:   1,
		Name: "Dog unknown",
	}

	//判断返回
	if name == "zs" {
		resp = &gw.DogResponse{
			Id:   1,
			Name: "Dog Xiaobai And Kele",
		}
	}

	return
}

func main() {
	//rpcServer := grpc.NewServer()
	//
	////调用 Register + XXX + ServiceServer的方法
	//gw.RegisterDogServiceServer(rpcServer, new(DogService))
	//
	//lis, err := net.Listen("tcp", "127.0.0.1:9099")
	//
	////	defer lis.Close()
	//if err != nil {
	//	fmt.Println("rpc serve listen fail")
	//}
	//rpcServer.Serve(lis)
	//
	//fmt.Println("rpc serve at 9090")

	//1.监听端口
	var addr = conf.SERVER_ADDR_RPC
	var listen, err = net.Listen("tcp", addr)
	if err != nil {
		fmt.Println("listen error")
	}

	defer listen.Close()

	fmt.Println("listen addr:", addr)

	//2.实例化grpc
	s := grpc.NewServer()

	//3.在gRPC上注册微服务
	u := &DogService{}
	gw.RegisterDogServiceServer(s, u)

	//4.启动服务端
	s.Serve(listen)

}
